package idx

import (
	"crypto/md5"
	"enode/store"
	"io"
	"os"
	"path/filepath"
)

type SingleFile struct {
	dataDir string
}

func NewSingleFile(dataDir string) *SingleFile {
	return &SingleFile{dataDir: dataDir}
}

func (f *SingleFile) PutPiece(key string, metaInfo *store.PieceMetaInfo, r io.Reader) (hash []byte, err error) {
	filePath := filepath.Join(f.dataDir, key)
	var fp *os.File
	fp, err = os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, store.FilePermission)
	if err != nil {
		return
	}
	defer func() {
		_ = fp.Close()
	}()
	hw := NewHashWriter(fp, md5.New())
	var _ int64
	_, err = io.Copy(hw, r)
	if err != nil {
		return
	}
	return hw.Hash(), nil
}

func (f *SingleFile) GetPiece(key string) (r io.ReadCloser, hash []byte, size int64, err error) {
	filePath := filepath.Join(f.dataDir, key)
	var fp *os.File
	fp, err = os.OpenFile(filePath, os.O_RDONLY, store.FilePermission)
	if err != nil {
		return
	}
	fs, _ := fp.Stat()
	return fp, []byte{}, fs.Size(), nil
}

func (f *SingleFile) DelPiece(key string) (err error) {
	filePath := filepath.Join(f.dataDir, key)
	_, err = os.Stat(filePath)
	if err != nil {
		return
	}
	return os.Remove(filePath)
}

func (f *SingleFile) Mode() string {
	return store.ModeSingleFile
}
